# -*- coding: utf-8 -*-
"""
@File    : sichuan_chengdu_policy
@Author  : caojy
@Time    : 25/01/13 11:47
"""
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanChengduPolicy(BaseTaxPolicySpider):
    name = 'sichuan_chengdu_policy'

    province = '四川省'
    city = '成都市'
    # county = '滑县'
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 100
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['成都市人民政府', "", "https://www.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市人民政府', "", "https://www.chengdu.gov.cn/gkml/qtwj/qtwj/column-index-1.shtml"],
            ['成都市经济和信息化局', "", "https://cdjx.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市经济和信息化局', "", "https://cdjx.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市民政局', "", "https://cdmzj.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市财政局', "", "https://cdcz.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市住房和城乡建设局', "", "https://cdzj.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市住房和城乡建设局', "", "https://cdzj.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市农业农村局', "", "https://cdagri.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市投资促进局', "", "https://cdtc.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市投资促进局', "", "https://cdtc.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市文化广电旅游局', "", "https://cdwglj.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市退役军人事务局', "", "https://tyjrswj.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市退役军人事务局', "", "https://tyjrswj.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市市场监督管理局', "", "https://scjg.chengdu.gov.cn/gkml/xzgfxwj/yx/detail-list/column-index-1.shtml"],
            ['成都市市场监督管理局', "", "http://scjg.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml"],
            ['成都市体育局', "", "https://cdsport.chengdu.gov.cn/gkml/qtwj/column-index-1.shtml?page=1"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//ul[@id='zc-info']//div[@onclick]"
        )
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath("""./@onclick""").re_first(r"open\('(.*?)'")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = response.meta.get('page') or 1
        total = response.xpath("""//script""").re_first(r"total:\s*(\d+)")
        total_page = math.ceil(int(total) / 10)
        if page < total_page:
            print(response.url, total_page, "page:", page)
            url = response.url.replace(f"index-{page}", f"index-{page+1}")
            yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, "page": page+1})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//div[@class='ele']/div[contains(text(), '发布日期')]/following-sibling::div/text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_chengdu_policy".split())
